import {
    request,
    AbstractBookCrawler,
    BasicBook,
    SearchBookResult,
    Book,
    BasicChapter,
    BookCrawlerTest,
    BookSource,
    getPathFromUrl,
    htmlToString,
    encodeUrl,
    RequestOptions,
    getAbsPath, RequestInputType,
} from "../../common/common_node.js";

class BookCrawler extends AbstractBookCrawler {

    options = {decoder: 'gbk'};

    async searchBook(keyword, pageNum) {
        function getBoolList($) {
            const bookArr = [];
            if ($('.zjlist').length > 0) {//存在目录
                bookArr.push(new BasicBook({
                    name: $("meta[property='og:novel:book_name']").attr('content'),
                    author: $("meta[property='og:novel:author']").attr('content'),
                    path: $("meta[property='og:novel:read_url']").attr('content').replace(this.source.bookBaseUrl, ''),
                }));
            } else {
                const trArr = $("#main tr");
                trArr.each(function (index, elem) {
                    if (index !== 0) {
                        let tds = $(elem).find("td");
                        let nameAndPath = tds.eq(0).find("a");
                        bookArr.push(new BasicBook({
                            name: nameAndPath.text(),
                            author: tds.eq(2).text(),
                            path: getPathFromUrl(nameAndPath.attr('href')),
                        }));
                    }
                })
            }
            return bookArr;
        }

        const url = `${this.source.searchBaseUrl}/modules/article/search.php?searchkey=${encodeUrl(keyword, "gb2312")}&page=${pageNum}`;
        const $ = await (await request(url, new RequestOptions({
            type: "webView",
            inputType: RequestInputType.filePath,
            ignoreUserAgent: true
        }))).doc();

        let bookArr = getBoolList($);
        const pageMax = $('#pagelink .last').text();
        return new SearchBookResult({
            pageNum: pageNum,
            pages: Number(pageMax ?? 1),
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();

        return new Book({
            name: $("meta[property='og:novel:book_name']").attr('content'),
            author: $("meta[property='og:novel:author']").attr('content'),
            path: path,
            intro: $("meta[property='og:description']").attr('content'),
            coverUrl: $("meta[property='og:image']").attr('content'),
            type: $("meta[property='og:novel:category']").attr('content'),
        });
    }

    async bookCatalog(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        const chapters = $('.zjlist a');
        let catalog = [];
        chapters.each(function (i, elem) {
            const item = $(elem);
            catalog.push(new BasicChapter({
                index: i,
                title: item.text(),
                path: getAbsPath(path, item.attr("href"))
            }));
        });
        return catalog;
    }

    async chapterContent(path) {
        const $ = await (await request(this.source.bookBaseUrl + path, this.options)).doc();
        let content = htmlToString($("#content").html());
        return content.replace(/67书吧[\s\S]*?最新章节！/g, '');
    }
}

const source = {
    "id": "free_book_js/14",
    "name": "67书吧",
    "portalUrl": "http://www.67shu.org",
    "searchBaseUrl": "http://www.67shu.org",
    "bookBaseUrl": "http://www.67shu.org",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true, keyword: "重生",
}).run();

